<script lang="ts" setup>
import { reactive, ref, watch, onMounted, nextTick } from 'vue';
import { ReturnTree } from '@whjxtech/jxtech-component';
import UserListSelectInput from './user-list-select-input.vue';
import UnitTreeCard from '/@/views/org/unit/component/unit-tree-card.vue';
import { ElMessage } from 'element-plus';

const UserListRef = ref();
const emit = defineEmits<{
  (e: 'update:visible', val: boolean): void;
  (e: 'ok', val: any[]): void;
}>();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  unitCode: {
    type: String,
    default: '',
  },
});
const visibleModelValue = ref(props.visible);
watch(
  () => props.visible,
  (val) => {
    visibleModelValue.value = val;
  }
);
watch(visibleModelValue, (val) => {
  emit('update:visible', val);
  if (val) {
    nextTick(() => {
      UserListRef.value.getUserListTableRef().loadTable();
    });
  }
});

const UserListDialogState = reactive({
  queryParam: { unitId: '10000' },
  loadUserTable: () => {
    UserListRef.value.getUserListTableRef().loadTable();
  },
  handleClose: () => {
    visibleModelValue.value = false;
  },
  onSaveButtonClick: () => {
    const pkList = UserListRef.value.selectionListData();
    if (pkList.length > 0) {
      emit('ok', pkList);
      visibleModelValue.value = false;
    } else {
      ElMessage({
        type: 'warning',
        message: '至少选中一项',
      });
    }
  },
  /**节点点击事件 */
  handleNodeClick: (treeData: ReturnTree<any>) => {
    UserListDialogState.queryParam.unitId = treeData.id;
    nextTick(() => UserListDialogState.loadUserTable());
  },
});
</script>
<template>
  <div class="jxtech-dialog-form">
    <slot></slot>
    <el-dialog
      v-model="visibleModelValue"
      title="选择用户"
      width="80%"
      :fullscreen="true"
      destroy-on-close
      :before-close="UserListDialogState.handleClose"
      append-to-body
    >
      <el-row :gutter="12">
        <el-col :span="6">
          <unit-tree-card @node-click="UserListDialogState.handleNodeClick"></unit-tree-card>
        </el-col>
        <el-col :span="18">
          <user-list-select-input
            :tableHeight="788"
            ref="UserListRef"
            :query-param="UserListDialogState.queryParam"
          ></user-list-select-input>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <jxtech-cancel-button @click="UserListDialogState.handleClose"></jxtech-cancel-button>
          <jxtech-ok-button @click="UserListDialogState.onSaveButtonClick"></jxtech-ok-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
